package mammuthus.web.service

import java.net.URLEncoder
import net.csdn.common.path.Url
import com.webdm.common.tools.CatchUtil
import mammuthus.web.bean.ShellResult

/**
 * 5/28/15 WilliamZhu(allwefantasy@gmail.com)
 */
trait DockerContainerConfigure {
  this: SlaveService =>

  def isDockerHostHaveBeenConfigure(hostName: String) = {
    val shellCommand = URLEncoder.encode(s"ip addr||ifconfig", "utf-8")
    val response = httpClient.get(new Url(shellURL).query(s"slaves=${hostName}&shellCommand=${shellCommand}"))
    val shellResult = generateShellResult(response)
    shellResult.taskInfos.filter(f => f.message.contains("mammuthusbr0")).size > 0
  }

  def startDockerContainerAgent(hostNames: String, id: String) = {

    val deploy = URLEncoder.encode(s"docker exec $id /data/1/usr/local/mammuthus-agent/bin/deploy.sh deploy", "utf-8")
    val response = httpClient.get(new Url(shellURL).query(s"slaves=${hostNames}&shellCommand=${deploy}"))

    val deployResult = generateShellResult(response)


    val start = URLEncoder.encode(s"docker exec $id /data/1/usr/local/mammuthus-agent/bin/deploy.sh start", "utf-8")

    val startReponse = httpClient.get(new Url(shellURL).query(s"slaves=${hostNames}&shellCommand=${start}"))

    val startResult = generateShellResult(startReponse)

    List(deployResult, startResult)
  }

  def configDockerConainerIp(query: String): ShellResult = {
    val configIpUrl = s"${masterUrl}/docker/container/ip/configure?${authTokenStr}"
    logger.info(s"config docker container ip: $configIpUrl ")
    val response = httpClient.get(new Url(configIpUrl).query(query))
    generateShellResult(response)
  }

  def configDockerContainerHost(hostNames: String, containerName: String, containerIP: String): ShellResult = {
    val shellCommand = URLEncoder.encode( s"""docker exec $containerName /bin/bash -c "echo '$containerIP $containerName' >> /etc/hosts"""", "utf-8")

    val response = httpClient.get(new Url(shellURL).query(s"slaves=${hostNames}&shellCommand=${shellCommand}"))
    generateShellResult(response)
  }

  def startContainer(hostName: String, id: String) = {
    val url = s"${masterUrl}/docker/container/start?slaves=${hostName}&id=$id"
    CatchUtil.getSrc(url, false)
  }

  def stopContainer(hostName: String, id: String) = {
    val url = s"${masterUrl}/docker/container/stop?slaves=${hostName}&id=$id"
    CatchUtil.getSrc(url, false)
  }

 def eanbleContainerConf(slaves:String) = {
   val url= s"${masterUrl}/conf/control?slaves=${slaves}"
   val response = httpClient.get(new Url(url))
   response.getContent
 }


}
